package com.example.demo.demos.gateway;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class GatewayFinder {
    public static String getGateway() {
        try {
            String os = System.getProperty("os.name").toLowerCase();
            String command = os.contains("win") ? "route print" : "route -n";
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
            );
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("0.0.0.0") || line.contains("Default Gateway")) {
                    String[] parts = line.trim().split("\\s+");
                    // Windows示例：匹配"0.0.0.0"行，网关在第3列
                    if (parts.length > 2 && parts[0].equals("0.0.0.0")) 
                        return parts[2];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}